package cn.itsource.org.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.query.PageList;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.utils.RedisService;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department,DepartmentQuery> implements IDepartmentService {

    //注入redis服务
    @Autowired
    private RedisService redisService;

    //注入Mapper层
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 分页
     * @param query
     * @return
     */
    @Override
    public PageList<Department> getAllByPage(DepartmentQuery query) {
        //1.传递分页的参数
        PageHelper.startPage(query.getPageNum(),query.getPageSize());

        //2.执行查询操作，查询所有
        List<Department> departments = departmentMapper.getAll(query);

        //3.使用分页工具类封装分页参数
        PageInfo<Department> pageInfo = new PageInfo<>(departments);

        //4.使用自己的分页工具类封装数据
        PageList<Department> pageListl = new PageList<>(pageInfo.getTotal(), pageInfo.getList());
        //5.返回数据
        return pageListl;
    }


    /**
     * 新增或者修改
     * @param department
     */
    @Override
    public void saveOrUpdate(Department department) {
        if(department.getId() == null){
            departmentMapper.insertSelective(department);

            System.out.println("自增主键id");
            System.out.println(department.getId());

            updateDept(department);

            }

        //6.修改数据
        departmentMapper.updateByPrimaryKeySelective(department);

        redisService.deleteRedisByKey("treeList");      //清空redis服务器中的缓存数据

    }

    /**
     * 格式化前端的parentids里面的数据     [3,8,9]
     * 转化为 dirpath              /3/8/9当前id
     * @param department
     */
    private void updateDept(Department department) {
        //1.拿到parentIds数据
        Long[] parentIds = department.getParentIds();
        //2.判断parentIds是否为空
        if (parentIds != null && parentIds.length > 0) {
            StringBuilder sb = new StringBuilder();
            //3.循环parentIds
            for (int i = 0; i < parentIds.length; i++) {
                sb.append("/" + parentIds[i]);
            }
            //4.将自增主键数据写入到dirpath字段中
            department.setDirPath(sb.toString() + "/" + department.getId());
            //5,设置parentId字段数据
            department.setParentId(parentIds[parentIds.length - 1]);
        }
    }


    @Override
    @CacheEvict(cacheNames = "dept",key = "'tree'")     //SpringCache注解版
    public void delete(Long id) {
        departmentMapper.deleteByPrimaryKey(id);

      //  redisService.deleteRedisByKey("treeList");        redis版

    }

    /**
     * json对象：{"key":"value"}
     * json数组：[{"key":"value"},{"key":"value"},{"key":"value"}]
     *
     * 缓存的目的：避免每次查询都要去数据库中查
     *      将数据缓存到redis，只要数据没有发生变化，就直接在redis中直接返回
     *
     * @return
     */
    @Override
    @Cacheable(cacheNames = "dept",key = "'tree'")
    public List<Department> treeDepts() {
        //第一次访问数据库，后面走redis
        //1.查询缓存服务器（redis）中的数据
        /*List<Department> treeList = redisService.getKeyObjectValue("treeList", List.class);
        //2.判空
        if(treeList == null){
            //2.1 查询数据库的内容
//            List<Department> departments = getDepartments();
//            treeList = departments;
            treeList = getDepartments();
            //2.2 将数据库中的内容存储到redis服务器中
            redisService.setStringKeyAndValue("treeList",treeList);
        }
        //3.返回数据
        return treeList;*/
        System.err.println("我tm来了。。");
        return getDepartments();
    }

    /**
     * 部门树方法抽取
     * @return
     */
    private List<Department> getDepartments() {
        //1.查询到所有的部门数据
        List<Department> departments = departmentMapper.selectAll();
        //2.定义一个空集合
        List<Department> treeList = new ArrayList<>();

        //3.将departments数据放入一个map集合中，方便查找
        Map<Long,Department> map = new HashMap();
        for(Department dept : departments){
            map.put(dept.getId(),dept);
        }

        for (Department dept : departments) {
            if(dept.getParentId()==null){
                //表示当前数据是一个顶级父类
                treeList.add(dept);
            }else{
                //表示当前数据是一个子部门
                //查找当前数据的上级部门
                Department department = map.get(dept.getParentId());
                //将当前循环的子类数据放到上级部门的Children中
                department.getChildren().add(dept);
            }
        }
        return treeList;
    }


    //父级部门
    @Override
    public List<Department> getParentDepts() {
        return departmentMapper.getParentDepts();
    }
}
